package dao

import (
	"RedWork/model"
	"fmt"
)
import _ "github.com/go-sql-driver/mysql"

//这个里面返回MySQL的err返回原生的
func AddUser(user model.UserInfo) (uid int, err error) {
	err = nil
	sqlStr := `insert into user_info(user_name, pass_word, phonenum, email, user_image) 
				values (?,?,?,?,?)`
	var newuser UserInfo
	newuser.UserName = user.UserName
	newuser.PassWord = user.PassWord
	newuser.PhoneNum = user.PhoneNum
	newuser.Email = user.Email
	_, err = DB.Exec(sqlStr, newuser.UserName, newuser.PassWord, newuser.PhoneNum, newuser.Email,
		newuser.UserImage)
	if err != nil {
		return 0, err
	}
	uid, err = QueryUserID(newuser.UserName)
	return
}

func QueryUserID(username string) (uid int, err error) {
	err = nil
	sqlStr := "select user_id from user_info where user_name = ?"
	err = DB.QueryRow(sqlStr, username).Scan(&uid)
	if err != nil {
		return 0, err
	}
	return
}

func QueryUserPW(username string) (password string, uid int, err error) {
	uid = 0
	password = ""
	err = nil
	fmt.Println(username)
	sqlStr := fmt.Sprintf("select user_id, pass_word from user_info where user_name='%s'", username)
	err = DB.QueryRow(sqlStr).Scan(&uid, &password)
	fmt.Println(uid, password)
	if err != nil {
		fmt.Println(err)
		return
	}
	return

}

func AddMoney(uid int, money string) (err error) {
	sqlStr := "UPDATE user_info SET user_info.money = user_info.money + ? WHERE `user_id` = ?"
	_, err = DB.Exec(sqlStr, money, uid)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(sqlStr)
	return
}

type UserInfoRes struct {
	UserID   int     `json:"user_id"`
	UserName string  `json:"user_name"`
	PhoneNum int     `json:"phone_num"`
	Email    string  `json:"email"`
	Image    string  `json:"image"`
	Money    float64 `json:"money"`
}

func QueryUserInfo(uid string) (info UserInfoRes) {
	sqlStr := "SELECT user_id, user_name, phonenum, email, user_image, money FROM user_info WHERE user_id = ?"
	row := DB.QueryRow(sqlStr, uid)
	err := row.Scan(
		&info.UserID,
		&info.UserName,
		&info.PhoneNum,
		&info.Email,
		&info.Image,
		&info.Money,
	)
	if err != nil {
		fmt.Println(err)
		return
	}
	return
}
